<template>
    <div class="">
        <h1>Promise.then()</h1>
        <input type="text" v-model="topic">
        <button @click=clickToPublish>clickToPublish</button>

        <div v-ripple>Click Me</div>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    components: {},
    data() {
        return {
            client: null,
            message: "111",
            topic: "shuangshuang", info: null
            // subsTopic: "sys/KHKFO2rfBXa0msY4/a2:cb:15:b8:28:e5/thing/event/property/post/requestRecord",
            // pubTopic: "sys/KHKFO2rfBXa0msY4/a2:cb:15:b8:28:e5/thing/service/requestRecord",
            // payload: { page: 1, limit: 20, action: "runRecord", sidx: "id", order: "desc" }
        };
    },
    created() { },
    mounted() {
        // async function fetchDataFromApi() {
        //     fetch('https://v2.jokeapi.dev/joke/Programming?type=single')
        //         .then(res => res.json())
        //         .then(json => console.log(json.joke));
        // }

        // fetchDataFromApi()
        //     .then(() => {
        //         console.log('Finished fetching data');
        //     });

        // this.createMQTT();


    },
    watch: {
        topic(newvalue, oldvalue) {
            console.log('newvalue', newvalue);
            this.client.subscribe(this.topic, () => {
                console.log('订阅了主题：', this.topic);
            })
        }
    },
    methods: {
        // await 必须用在 async 中
        // async 修饰函数
        // await 修饰异步操作，阻止主进程继续往下走，执行完 await 修饰的语句后才能继续往下走
        async test1() {
            let str = "";
            await fetch('https://v2.jokeapi.dev/joke/Programming?type=single')
                .then(res => res.json())
                .then(json => {
                    console.log(json.joke)
                    str = json.joke;
                })
                .then(() => {
                    // console.log(' str ', str);
                    console.log('----------------');
                })
        },
        // 生成随机字符
        randomName(len) {
            var len = len || 23;
            var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
            var maxPos = chars.length;
            var str = "";
            for (let i = 0; i < len; i++) {
                str += chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return new Date().getTime() + str;
        },
        createMQTT() {
            const mqtt = require("mqtt");

            // let url = "wss://www.huanchenxinnengyuan.com/mqtt";
            let url = "ws://broker.emqx.io:8083/mqtt";
            let MQTT_OPTIONS = {
                connectTimeout: 4000,
                reconnectPeriod: 1000,
                clientId: 'emqx_test',
                username: 'emqx_test',
                password: 'emqx_test',
                clean: true,
            }
            MQTT_OPTIONS.clientId = this.randomName(16);//改变clientid
            this.client = mqtt.connect(url, MQTT_OPTIONS);

            this.client.on("connect", () => {
                console.log('连接成功');
            });
            this.client.on('message', (topic, msg) => {
                console.log(`topic: ${topic}`);
                console.log(`message: ${msg.toString()}`);
                this.message = msg;
            });
            this.client.on("close", () => {
                console.log('已经断开连接');
            });
            // this.client.subscribe(this.topic);
            // // 订阅主题、收到消息
            this.client.subscribe(this.topic, () => {
                console.log('订阅了主题：', this.topic);
            })
        },
        clickToPublish() {
            this.client.publish(this.topic, "" + Date.now());
        },
        testPromise() {
            // 微任务：Promise（promise把异步变成同步），async/await
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve("hello");
                    reject("error world");
                }, 2000);
            }).then((res) => {
                console.log(res);
            }).catch((err) => {
                console.log(err);
            });
        },
        requestRunRecords() {
            // setTimeout(() => {
            //     this.client.publish(this.topic, "" + Date.now());
            // }, 2000);
            // setInterval(() => {
            //     console.log(this.message);
            // }, 500);
        },
        fetchData() {
            const url = "'https://www.runoob.com/try/ajax/json_demo.json'";
            // axios.get(url)
            //     .then(response => {
            //         console.log(response);
            //     })
            //     .catch(error => {
            //         console.error('请求出错:', error);
            //     });

            axios
                .get('https://www.runoob.com/try/ajax/json_demo.json')
                .then(response => (this.info = response))
                .catch(function (error) { // 请求失败处理
                    console.log(error);
                });
        }
    },
}
</script>
<style scoped></style>